import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../data/models/todo_model.dart';

/// Todo任务卡片组件
/// 显示单个任务的详细信息，支持状态切换和快速操作
class TodoCardWidget extends ConsumerStatefulWidget {
  final TodoModel todo;
  final VoidCallback? onTap;
  final Function(TodoStatus)? onStatusChanged;
  final Function(TodoModel)? onEdit;
  final Function(TodoModel)? onDelete;
  final bool isSelected;

  const TodoCardWidget({
    super.key,
    required this.todo,
    this.onTap,
    this.onStatusChanged,
    this.onEdit,
    this.onDelete,
    this.isSelected = false,
  });

  @override
  ConsumerState<TodoCardWidget> createState() => _TodoCardWidgetState();
}

class _TodoCardWidgetState extends ConsumerState<TodoCardWidget> {
  bool _isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      elevation: widget.isSelected ? 4 : 1,
      color: widget.isSelected ? Colors.blue.shade50 : null,
      child: InkWell(
        onTap: widget.onTap,
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 任务头部信息
              _buildTaskHeader(),

              const SizedBox(height: 8),

              // 任务描述
              if (widget.todo.description?.isNotEmpty == true) ...[
                Text(
                  widget.todo.description!,
                  style: TextStyle(
                    color: Colors.grey.shade600,
                    fontSize: 14,
                  ),
                  maxLines: _isExpanded ? null : 2,
                  overflow: _isExpanded ? null : TextOverflow.ellipsis,
                ),
                if (widget.todo.description!.length > 100)
                  TextButton(
                    onPressed: () => setState(() => _isExpanded = !_isExpanded),
                    child: Text(_isExpanded ? '收起' : '展开'),
                  ),
                const SizedBox(height: 8),
              ],

              // 任务元信息
              _buildTaskMetadata(),

              // 展开的详细信息
              if (_isExpanded) ...[
                const Divider(height: 20),
                _buildExpandedContent(),
              ],
            ],
          ),
        ),
      ),
    );
  }

  /// 构建任务头部
  Widget _buildTaskHeader() {
    return Row(
      children: [
        // 状态指示器
        _buildStatusIndicator(),
        const SizedBox(width: 12),

        // 任务标题
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                widget.todo.title,
                style: TextStyle(
                  fontWeight: FontWeight.w500,
                  fontSize: 16,
                  decoration: widget.todo.status == TodoStatus.done
                      ? TextDecoration.lineThrough
                      : null,
                  color: widget.todo.status == TodoStatus.done
                      ? Colors.grey.shade600
                      : null,
                ),
              ),
              Container(
                margin: const EdgeInsets.only(top: 4),
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                decoration: BoxDecoration(
                  color: _getTypeColor(widget.todo.todoType)
                      .withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Text(
                  _getTypeText(widget.todo.todoType),
                  style: TextStyle(
                    fontSize: 10,
                    color: _getTypeColor(widget.todo.todoType),
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),
        ),

        // 优先级标签
        _buildPriorityChip(widget.todo.priority),

        const SizedBox(width: 8),

        // 操作菜单
        PopupMenuButton<String>(
          onSelected: _handleMenuAction,
          itemBuilder: (context) => [
            PopupMenuItem(
              value: 'edit',
              child: Row(
                children: [
                  const Icon(Icons.edit, size: 16),
                  const SizedBox(width: 8),
                  const Text('编辑'),
                ],
              ),
            ),
            PopupMenuItem(
              value: 'duplicate',
              child: Row(
                children: [
                  const Icon(Icons.copy, size: 16),
                  const SizedBox(width: 8),
                  const Text('复制'),
                ],
              ),
            ),
            const PopupMenuDivider(),
            PopupMenuItem(
              value: 'delete',
              child: Row(
                children: [
                  const Icon(Icons.delete, size: 16, color: Colors.red),
                  const SizedBox(width: 8),
                  const Text('删除', style: TextStyle(color: Colors.red)),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建状态指示器
  Widget _buildStatusIndicator() {
    return GestureDetector(
      onTap: () => _showStatusSelector(),
      child: Container(
        width: 12,
        height: 12,
        decoration: BoxDecoration(
          color: _getStatusColor(widget.todo.status),
          shape: BoxShape.circle,
          border: Border.all(
            color: _getStatusColor(widget.todo.status).withValues(alpha: 0.3),
            width: 2,
          ),
        ),
        child: widget.todo.status == TodoStatus.done
            ? const Icon(
                Icons.check,
                size: 8,
                color: Colors.white,
              )
            : null,
      ),
    );
  }

  /// 构建任务元信息
  Widget _buildTaskMetadata() {
    return Row(
      children: [
        // 负责人
        if (widget.todo.assigneeName != null) ...[
          Icon(Icons.person, size: 14, color: Colors.grey.shade600),
          const SizedBox(width: 4),
          SelectableText(
            widget.todo.assigneeName!,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey.shade600,
            ),
          ),
          const SizedBox(width: 16),
        ],

        // 截止日期
        if (widget.todo.dueDate != null) ...[
          Icon(
            Icons.schedule,
            size: 14,
            color: _isOverdue() ? Colors.red : Colors.grey.shade600,
          ),
          const SizedBox(width: 4),
          SelectableText(
            _formatDeadline(),
            style: TextStyle(
              fontSize: 12,
              color: _isOverdue() ? Colors.red : Colors.grey.shade600,
              fontWeight: _isOverdue() ? FontWeight.w500 : null,
            ),
          ),
          const Spacer(),
        ] else
          const Spacer(),

        // 状态标签
        _buildStatusChip(widget.todo.status),
      ],
    );
  }

  /// 构建展开的详细内容
  Widget _buildExpandedContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 详细信息行
        if (widget.todo.estimatedHours != null ||
            widget.todo.actualHours != null) ...[
          const SelectableText(
            '详细信息',
            style: TextStyle(
              fontWeight: FontWeight.w500,
              fontSize: 14,
            ),
          ),
          const SizedBox(height: 8),

          // 工时信息
          if (widget.todo.estimatedHours != null ||
              widget.todo.actualHours != null)
            Row(
              children: [
                if (widget.todo.estimatedHours != null) ...[
                  const Icon(Icons.schedule, size: 14),
                  const SizedBox(width: 4),
                  SelectableText(
                    '预计: ${widget.todo.estimatedHours}h',
                    style: const TextStyle(fontSize: 12),
                  ),
                  const SizedBox(width: 16),
                ],
                if (widget.todo.actualHours != null) ...[
                  const Icon(Icons.timer, size: 14),
                  const SizedBox(width: 4),
                  SelectableText(
                    '实际: ${widget.todo.actualHours}h',
                    style: const TextStyle(fontSize: 12),
                  ),
                ],
              ],
            ),

          const SizedBox(height: 4),

          // 创建时间
          Row(
            children: [
              const Icon(Icons.access_time, size: 14),
              const SizedBox(width: 4),
              SelectableText(
                '创建于: ${_formatDateTime(widget.todo.createTime)}',
                style: const TextStyle(fontSize: 12),
              ),
            ],
          ),
        ],

        const SizedBox(height: 12),

        // 快速操作按钮
        Row(
          children: [
            _buildQuickActionButton(
              '开始',
              Icons.play_arrow,
              Colors.green,
              widget.todo.status != TodoStatus.inProgress,
              () => _updateStatus(TodoStatus.inProgress),
            ),
            const SizedBox(width: 8),
            _buildQuickActionButton(
              '完成',
              Icons.check,
              Colors.blue,
              widget.todo.status != TodoStatus.done,
              () => _updateStatus(TodoStatus.done),
            ),
            const SizedBox(width: 8),
            _buildQuickActionButton(
              '暂停',
              Icons.pause,
              Colors.orange,
              widget.todo.status != TodoStatus.blocked,
              () => _updateStatus(TodoStatus.blocked),
            ),
            const Spacer(),
            TextButton(
              onPressed: () => setState(() => _isExpanded = false),
              child: const Text('收起'),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建快速操作按钮
  Widget _buildQuickActionButton(
    String label,
    IconData icon,
    Color color,
    bool enabled,
    VoidCallback onPressed,
  ) {
    return OutlinedButton.icon(
      onPressed: enabled ? onPressed : null,
      icon: Icon(icon, size: 16),
      label: Text(label),
      style: OutlinedButton.styleFrom(
        foregroundColor: color,
        side: BorderSide(color: color.withValues(alpha: 0.5)),
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
        minimumSize: const Size(0, 32),
      ),
    );
  }

  /// 构建优先级标签
  Widget _buildPriorityChip(Priority priority) {
    Color color = _getPriorityColor(priority);
    String text = _getPriorityText(priority);

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: color.withValues(alpha: 0.3)),
      ),
      child: SelectableText(
        text,
        style: TextStyle(
          fontSize: 10,
          color: color,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  /// 构建状态标签
  Widget _buildStatusChip(TodoStatus status) {
    Color color = _getStatusColor(status);
    String text = _getStatusText(status);

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(10),
      ),
      child: SelectableText(
        text,
        style: TextStyle(
          fontSize: 10,
          color: color,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  /// 显示状态选择器
  void _showStatusSelector() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '更改任务状态',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(height: 16),
            ...TodoStatus.values.map((status) => ListTile(
                  leading: Container(
                    width: 16,
                    height: 16,
                    decoration: BoxDecoration(
                      color: _getStatusColor(status),
                      shape: BoxShape.circle,
                    ),
                    child: status == TodoStatus.done
                        ? const Icon(
                            Icons.check,
                            size: 12,
                            color: Colors.white,
                          )
                        : null,
                  ),
                  title: Text(_getStatusText(status)),
                  selected: status == widget.todo.status,
                  onTap: () {
                    Navigator.pop(context);
                    _updateStatus(status);
                  },
                )),
          ],
        ),
      ),
    );
  }

  /// 处理菜单操作
  void _handleMenuAction(String action) {
    switch (action) {
      case 'edit':
        if (widget.onEdit != null) {
          widget.onEdit!(widget.todo);
        }
        break;
      case 'duplicate':
        // 实现复制功能
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('复制功能开发中...')),
        );
        break;
      case 'delete':
        _confirmDelete();
        break;
    }
  }

  /// 确认删除
  void _confirmDelete() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除任务「${widget.todo.title}」吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              if (widget.onDelete != null) {
                widget.onDelete!(widget.todo);
              }
            },
            child:
                const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  /// 更新状态
  void _updateStatus(TodoStatus status) {
    if (widget.onStatusChanged != null) {
      widget.onStatusChanged!(status);
    }
  }

  /// 获取状态颜色
  Color _getStatusColor(TodoStatus status) {
    switch (status) {
      case TodoStatus.todo:
        return Colors.grey;
      case TodoStatus.inProgress:
        return Colors.blue;
      case TodoStatus.done:
        return Colors.green;
      case TodoStatus.blocked:
        return Colors.red;
    }
  }

  /// 获取状态文本
  String _getStatusText(TodoStatus status) {
    switch (status) {
      case TodoStatus.todo:
        return '待办';
      case TodoStatus.inProgress:
        return '进行中';
      case TodoStatus.done:
        return '已完成';
      case TodoStatus.blocked:
        return '阻塞';
    }
  }

  /// 获取优先级颜色
  Color _getPriorityColor(Priority priority) {
    switch (priority) {
      case Priority.low:
        return Colors.green;
      case Priority.medium:
        return Colors.orange;
      case Priority.high:
        return Colors.red;
    }
  }

  /// 获取优先级文本
  String _getPriorityText(Priority priority) {
    switch (priority) {
      case Priority.low:
        return '低';
      case Priority.medium:
        return '中';
      case Priority.high:
        return '高';
    }
  }

  /// 获取类型颜色
  Color _getTypeColor(TodoType type) {
    switch (type) {
      case TodoType.communication:
        return Colors.blue;
      case TodoType.schedule:
        return Colors.green;
      case TodoType.document:
        return Colors.orange;
      case TodoType.dataSource:
        return Colors.purple;
      case TodoType.develop:
        return Colors.red;
      case TodoType.test:
        return Colors.teal;
      case TodoType.uat:
        return Colors.indigo;
      case TodoType.release:
        return Colors.pink;
    }
  }

  /// 获取类型文本
  String _getTypeText(TodoType type) {
    switch (type) {
      case TodoType.communication:
        return '沟通确认';
      case TodoType.schedule:
        return '排期安排';
      case TodoType.document:
        return '文档编写';
      case TodoType.dataSource:
        return '数据源核查';
      case TodoType.develop:
        return '开发实现';
      case TodoType.test:
        return '测试验证';
      case TodoType.uat:
        return 'UAT验收';
      case TodoType.release:
        return '发布上线';
    }
  }

  /// 是否过期
  bool _isOverdue() {
    if (widget.todo.dueDate == null) return false;
    return widget.todo.dueDate!.isBefore(DateTime.now()) &&
        widget.todo.status != TodoStatus.done;
  }

  /// 格式化截止日期
  String _formatDeadline() {
    if (widget.todo.dueDate == null) return '';

    final now = DateTime.now();
    final deadline = widget.todo.dueDate!;
    final difference = deadline.difference(now).inDays;

    if (difference < 0) {
      return '已逾期${-difference}天';
    } else if (difference == 0) {
      return '今天截止';
    } else if (difference == 1) {
      return '明天截止';
    } else if (difference <= 7) {
      return '$difference天后截止';
    } else {
      return '${deadline.month}/${deadline.day}';
    }
  }

  /// 格式化日期时间
  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }
}
